package com.haima.sage.bigdata.api.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.util.DigestUtils;

public class SignUtils {
    public static String digest(String secret, String requestURI, Map<String, ?> params,
                                String appKey, String userId, String userName, Long timestamp) {
        List<String> keys = new ArrayList<>();
        if (params != null) {
            keys.addAll(params.keySet());
            Collections.sort(keys);
        }
        StringBuilder buf = new StringBuilder();
        buf.append(secret);
        buf.append(requestURI).append("?");
        buf.append("appkey=").append(appKey);
        buf.append("&appUserId=").append(userId);
        buf.append("&appUserName=").append(userName);
        buf.append("&timestamp=").append(timestamp);

        if (params != null) {
            for (String key : keys) {
                buf.append("&").append(key).append("=");
                Object value = params.get(key);
                if (value != null) {
                    buf.append(value.toString());
                }
            }
        }
        System.out.println(buf.toString());
        return DigestUtils.md5DigestAsHex(buf.toString().getBytes());
    }


    public static String digest(String secret, String requestURI, String body) {
        StringBuilder buf = new StringBuilder();
        buf.append(secret);
        buf.append(requestURI).append("?");
        buf.append("body=").append(body);
        System.out.println(buf.toString());
        return DigestUtils.md5DigestAsHex(buf.toString().getBytes());
    }

}
